package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.SeriesBannerAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.BaiDuLocationInfo;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.entity.TelInfo;
import com.chexiehui.jc.event.CarCompareRecodeDeleteEvent;
import com.chexiehui.jc.event.GlobalFollowSeriesEvent;
import com.chexiehui.jc.mvp.car.CarSeriesDetailsCovenant;
import com.chexiehui.jc.mvp.car.CarSeriesDetailsPresenter;
import com.chexiehui.jc.realm.CarInfoDao;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.FixedSpeedScroller;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.utils.SoftKeyboardFixerForFullscreen;
import com.chexiehui.jc.widget.CustomInquiryPopup;
import com.chexiehui.jc.widget.CustomStageBuyCarPopup;
import com.chexiehui.jc.widget.CustomXPopupImageLoader;
import com.chexiehui.jc.widget.LoadingLayout;
import com.lxj.xpopup.XPopup;
import com.tmall.ultraviewpager.UltraViewPager;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 在售车辆详情
 */
public class CarSeriesDetailsBankActivity extends BaseMvpActivity<CarSeriesDetailsPresenter> implements View.OnClickListener,
        CarSeriesDetailsCovenant.View, CustomStageBuyCarPopup.ICustomStageBuyCarPopupListener, CustomInquiryPopup.ICustomInquiryPopupListener {
    @BindView(R.id.ultra_banner)
    UltraViewPager ultraViewPager;
    @BindView(R.id.iv_car_image)
    ImageView ivCarImage;
    @BindView(R.id.tv_car_name)
    TextView tvCarName;
    @BindView(R.id.tv_car_params)
    TextView tvCarParams;
    @BindView(R.id.tv_car_price)
    TextView tvCarPrice;
    @BindView(R.id.tv_car_guidance_price)
    TextView tvCarGuidancePrice;
    @BindView(R.id.tv_parameter_config)
    TextView tvParameterConfig;
    @BindView(R.id.tv_car_forum)
    TextView tvCarForum;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.tv_model_compare)
    TextView tvModelCompare;
    @BindView(R.id.tv_contact_sales)
    TextView tvContactSales;
    @BindView(R.id.tv_stages_buy)
    TextView tvStagesBuy;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.rtv_choose_compare_count)
    RadiusTextView rtv_choose_compare_count;

    private TextView tvCity;
    private ImageView ivFollow;
    private ImageView ivShare;

    private ArrayList<CarInfo> carModelData;
    private CommonAdapter<CarInfo> carModelAdapter;
    private String seriesId;
    private CarSeriesInfo seriesInfo;
    private BaiDuLocationInfo nowCity;

    private CustomInquiryPopup customInquiryPopup;
    private CustomStageBuyCarPopup customStageBuyCarPopup;
    private String salespersonTel;
    private SeriesBannerAdapter seriesBannerAdapter;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            seriesId = bundle.getString("seriesId");
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("选车");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_car_series_details;
    }

    @Override
    protected void initView(Bundle var1) {
        SoftKeyboardFixerForFullscreen.assistActivity(this);
        loadingLayout.setStatus(LoadingLayout.Loading);
        carModelData = new ArrayList<>();
        recycler.setLayoutManager(new LinearLayoutManager(mContext));
        recycler.setAdapter(carModelAdapter = new CommonAdapter<CarInfo>(mContext, R.layout.item_car_brand_model, carModelData) {
            @Override
            protected void convert(ViewHolder viewHolder, CarInfo item, int position) {
                viewHolder.setText(R.id.tv_item_params, item.getCustomerTitle());
                if (position > 0 && carModelData.get(position - 1).getCustomerTitle().equals(item.getCustomerTitle())) {
                    viewHolder.getView(R.id.tv_item_params).setVisibility(View.GONE);
                } else {
                    viewHolder.getView(R.id.tv_item_params).setVisibility(View.VISIBLE);
                }
                viewHolder.setText(R.id.tv_item_name, item.getShowTitle());
                viewHolder.setText(R.id.tv_item_price, item.getNewPriceStrUnit());
                viewHolder.setText(R.id.tv_item_follow, item.getFollowRateStr());
                viewHolder.setText(R.id.tv_car_price, "车主价：" + item.getNewPriceStrUnit());
                viewHolder.setText(R.id.tv_item_guidance_price, "指导价：" + item.getNewPriceStrUnit());
                viewHolder.getView(R.id.tv_item_inquiry_price).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        showInquiryPopup(item);
                    }
                });
                RadiusTextView tv_item_model_compare = viewHolder.getView(R.id.tv_item_model_compare);
                CarInfo c = AppApplication.getInstances().getCarInfoDao().queryBuilder()
                        .where(CarInfoDao.Properties.Id.eq(item.getId()))
                        .unique();
                tv_item_model_compare.setSelected(c != null);
                tv_item_model_compare.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        changeChooseCompareIds(item);
                    }
                });
            }
        });
        carModelAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(CarModelDetailsActivity.class, new BundleBuilder()
                        .putString("seriesId", getSeriesId())
                        .putString("carModelId", carModelData.get(position).getId())
                        .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        loadingLayout.setOnReloadListener(v -> mvpPresenter.getSeriesInfo());
        mvpPresenter.getSeriesInfo();
        mvpPresenter.getSalespersonTel();
    }

    private void changeChooseCompareIds(CarInfo item) {
        CarInfo c = AppApplication.getInstances().getCarInfoDao().queryBuilder()
                .where(CarInfoDao.Properties.Id.eq(item.getId()))
                .unique();
        if (c != null) {
            AppApplication.getInstances().getCarInfoDao().delete(item);
        } else {
            AppApplication.getInstances().getCarInfoDao().insert(item);
        }
        carModelAdapter.notifyDataSetChanged();
        setShowCompareCount();
    }

    private void setShowCompareCount() {
        long count = AppApplication.getInstances().getCarInfoDao().queryBuilder().count();
        rtv_choose_compare_count.setText(count + "");
        rtv_choose_compare_count.setVisibility(count > 0 ? View.VISIBLE : View.GONE);
    }

    private void setHeadInfo() {
        initBanner();
        tvCarName.setText(seriesInfo.getName());
        tvCarParams.setText(seriesInfo.getFactoryName() + "/" + seriesInfo.getSizeTypeStr());
        tvCarPrice.setText(seriesInfo.getPriceMaxMinStr());
        View rightAction = View.inflate(mContext, R.layout.layout_title_right_action_series_details, null);
        tvCity = rightAction.findViewById(R.id.tv_now_city);
        ivFollow = rightAction.findViewById(R.id.iv_follow);
        ivFollow.setImageResource(seriesInfo.isFollow() ? R.mipmap.ic_heart_s : R.mipmap.ic_heart_u);
        ivShare = rightAction.findViewById(R.id.iv_share);
        tvCity.setOnClickListener(this);
        ivFollow.setOnClickListener(this);
        ivShare.setOnClickListener(this);
        tvCity.setText("正在定位");
        titleBar.setTitleMainText("").addRightAction(titleBar.new ViewAction(rightAction));
        rtv_choose_compare_count.setVisibility(View.GONE);
        setShowCompareCount();
        requestAppPermissions();
    }

    private void initBanner() {
        if (seriesInfo.getImgs().size() > 0) {
            ultraViewPager.setVisibility(View.VISIBLE);
            ivCarImage.setVisibility(View.GONE);
            ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
            try {
                Field mField;
                mField = ViewPager.class.getDeclaredField("mScroller");
                mField.setAccessible(true);
                FixedSpeedScroller mScroller =
                        new FixedSpeedScroller(mContext, new AccelerateInterpolator());
                mScroller.setmDuration(1000);
                mField.set(ultraViewPager.getViewPager(), mScroller);
            } catch (Exception e) {
            }
            ultraViewPager.setAutoMeasureHeight(false);
            seriesBannerAdapter = new SeriesBannerAdapter(seriesInfo.getImgs(), (url, isVideo) -> {
                if (isVideo) {
                    VideoPlayActivity.start(CarSeriesDetailsBankActivity.this, seriesInfo.getName(), url);
                } else {
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(null, url, new CustomXPopupImageLoader())
                                .show();
                    } catch (Exception e) {
                    }
                }
            });
            ultraViewPager.setAdapter(seriesBannerAdapter);
            //内置indicator初始化
            ultraViewPager.initIndicator();
            //设置indicator样式
            ultraViewPager.getIndicator()
                    .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                    .setFocusColor(ContextCompat.getColor(mContext, R.color.colorWhite))
                    .setNormalColor(ContextCompat.getColor(mContext, R.color.c_999999))
                    .setRadius(SizeUtils.dp2px(4));
            //设置indicator对齐方式
            ultraViewPager.getIndicator().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            ultraViewPager.getIndicator().setMargin(0, 0, 0, SizeUtils.dp2px(10));
            //构造indicator,绑定到UltraViewPager
            ultraViewPager.getIndicator().build();
            //设定页面循环播放
            ultraViewPager.setInfiniteLoop(true);
            //设定页面自动切换  间隔5秒
            ultraViewPager.setAutoScroll(5000);
        } else {
            ultraViewPager.setVisibility(View.GONE);
            ivCarImage.setVisibility(View.VISIBLE);
            GlideUtil.loadImageViewCrop(mContext, seriesInfo.getImg(), ivCarImage, R.drawable.shape_square, R.drawable.shape_square);
            ivCarImage.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View view) {
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(ivCarImage, seriesInfo.getImg(), new CustomXPopupImageLoader())
                                .show();
                    } catch (Exception e) {
                    }
                }
            });
        }
    }

    private void requestAppPermissions() {
        AndPermission.with(this)
                .permission(Permission.LOCATION, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        if (!AppApplication.getInstances().getLocationService().isStart()) {
                            AppApplication.getInstances().getLocationService().start();
                        }
                        AppApplication.getInstances().getLocationService().registerListener(mListener);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权位置服务和访问文件的权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                BDLocation location = (BDLocation) msg.obj;
                nowCity = new BaiDuLocationInfo(location.getCity(), location.getLatitude(), location.getLongitude());
                tvCity.setText(location.getCity());
                AppApplication.getInstances().getLocationService().unregisterListener(mListener);
            }
        }
    };

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                if (!StringUtils.isTrimEmpty(location.getCity())) {
                    Message msg = new Message();
                    msg.obj = location;
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }

        @Override
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
            LogUtils.e("定位失败");
        }
    };

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        handler = null;
        AppApplication.getInstances().getLocationService().unregisterListener(mListener);
        mListener = null;
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        if (NoDoubleClickUtils.isDoubleClick()) return;
        switch (v.getId()) {
            case R.id.tv_now_city:
                startActivityForResult(ChooseCityActivity.class, 300);
                break;
            case R.id.iv_follow:
                mvpPresenter.doFollowSeries();
                break;
            case R.id.iv_share:
                break;
        }

    }

    @OnClick({R.id.tv_parameter_config,
            R.id.tv_car_forum, R.id.tv_model_compare, R.id.tv_contact_sales, R.id.tv_stages_buy,
            R.id.rtv_goto_inquiry})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_parameter_config:
                startActivity(CarBrandParameterActivity.class,
                        new BundleBuilder()
                                .putSerializable("compareList", carModelData)
                                .create());
                break;
            /*case R.id.tv_video_introduce:
                break;
            case R.id.tv_differential_config:
                startActivity(CarBrandDifferentConfigActivity.class);
                break;*/
            case R.id.tv_car_forum:
                if (StringUtils.isTrimEmpty(seriesInfo.getForumId())) {
                    showToast("暂无论坛");
                } else {
                    startActivity(ForumTribuneDetailsActivity.class, new BundleBuilder()
                            .putString("forumId", seriesInfo.getForumId())
                            .create());
                }
                break;
            case R.id.tv_model_compare:
                startActivity(CarModelCompareActivity.class);
                break;
            case R.id.tv_contact_sales:
                if (StringUtils.isTrimEmpty(salespersonTel)) {
                    showToast("暂无销售电话");
                } else {
                    callPhone(salespersonTel);
                }
                break;
            case R.id.tv_stages_buy:
                showStageBuyCarPopup(null);
                break;
            case R.id.rtv_goto_inquiry:
                showInquiryPopup(null);
                break;
        }
    }

    private void callPhone(String phone) {
        AndPermission.with(this)
                .permission(Permission.PHONE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PhoneUtils.call(phone);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权电话权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    private void showInquiryPopup(CarInfo carInfo) {
        if (customInquiryPopup == null) {
            customInquiryPopup = new CustomInquiryPopup(mContext);
            customInquiryPopup.setListener(this);
        }
        if (carInfo == null) {
            if (carModelData != null && carModelData.size() > 0) {
                customInquiryPopup.initCarModel(carModelData.get(0));
            } else {
                customInquiryPopup.initCarModel(null);
            }
        } else {
            customInquiryPopup.initCarModel(carInfo);
        }
        if (nowCity != null) {
            customInquiryPopup.initCity(nowCity);
        }
        new XPopup.Builder(mContext)
                .autoOpenSoftInput(false)
                .autoFocusEditText(false)
                .asCustom(customInquiryPopup)
                .show();
    }

    private void showStageBuyCarPopup(CarInfo carInfo) {
        if (customStageBuyCarPopup == null) {
            customStageBuyCarPopup = new CustomStageBuyCarPopup(mContext);
            customStageBuyCarPopup.setListener(this);
        }
        if (carInfo == null) {
            if (carModelData != null && carModelData.size() > 0) {
                customStageBuyCarPopup.initCarModel(carModelData.get(0));
            } else {
                customStageBuyCarPopup.initCarModel(null);
            }
        } else {
            customStageBuyCarPopup.initCarModel(carInfo);
        }
        if (nowCity != null) {
            customStageBuyCarPopup.initCity(nowCity);
        }
        new XPopup.Builder(mContext)
                .autoOpenSoftInput(false)
                .autoFocusEditText(false)
                .asCustom(customStageBuyCarPopup)
                .show();
    }

    @Override
    protected CarSeriesDetailsPresenter createPresenter() {
        return new CarSeriesDetailsPresenter(this);
    }

    @Override
    public void onGetSeriesInfoSuccess(BaseModel<CarSeriesInfo> successResult) {
        if (loadingLayout.getStatus() == LoadingLayout.Loading) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        seriesInfo = successResult.getData();
        setHeadInfo();
        carModelData.clear();
        for (int i = 0; i < seriesInfo.getCarBrieflies().size(); i++) {
            for (int j = 0; j < seriesInfo.getCarBrieflies().get(i).getCarList().size(); j++) {
                seriesInfo.getCarBrieflies().get(i).getCarList().get(j).setCustomerTitle(seriesInfo.getCarBrieflies().get(i).getTitle());
            }
            carModelData.addAll(seriesInfo.getCarBrieflies().get(i).getCarList());
        }
        carModelAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetSeriesInfoFailure(BaseModel<Object> failureResult) {
        if (failureResult.getResultCode() == Constants.PAGE_DATA_EMPTY) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public void onAddInstallmentSuccess(BaseModel<Object> successResult) {
        showLongToast("申请已提交，销售顾问会尽快与您联系！");
        customStageBuyCarPopup.dismiss();
        customStageBuyCarPopup.releaseObj();
        customStageBuyCarPopup = null;
    }

    @Override
    public void onAddInstallmentFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onAddShopInquirySuccess(BaseModel<Object> successResult) {
        showLongToast("申请已提交，销售顾问会尽快与您联系！");
        customInquiryPopup.dismiss();
        customInquiryPopup.releaseObj();
        customInquiryPopup = null;
    }

    @Override
    public void onAddShopInquiryFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onGetSalespersonTelSuccess(BaseModel<TelInfo> successResult) {
        if (successResult.getData() != null) {
            salespersonTel = successResult.getData().getTel();
        }

    }

    @Override
    public void onGetSalespersonTelFailure(BaseModel<Object> failureResult) {

    }


    @Subscribe
    public void onGlobalFollowSeriesEvent(GlobalFollowSeriesEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getSeriesId())) {
            if (event.getSeriesId().equals(getSeriesId())) {
                seriesInfo.setFollow(event.isFollow());
                ivFollow.setImageResource(seriesInfo.isFollow() ? R.mipmap.ic_heart_s : R.mipmap.ic_heart_u);
            }
        }
    }

    @Override
    public void onDoFollowSeriesSuccess(BaseModel<Object> successResult) {
        EventBus.getDefault().post(new GlobalFollowSeriesEvent(getSeriesId(), !seriesInfo.isFollow()));
    }

    @Override
    public void onDoFollowSeriesFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public String getSeriesId() {
        return seriesId;
    }

    @Override
    public void onStageBuyCarPopupCallChooseModel() {
        startActivityForResult(ChooseCarModelActivity.class, 10,
                new BundleBuilder().putSerializable("seriesInfo", seriesInfo).create());
    }

    @Override
    public void onStageBuyCarPopupCallChooseCity() {
        startActivityForResult(ChooseCityActivity.class, 11);
    }

    @Override
    public void onStageBuyCarPopupCallChooseMerchant() {
        if (customStageBuyCarPopup != null) {
            if (customStageBuyCarPopup.getChooseModel() == null) {
                showToast("请选择车型");
                return;
            }
            if (customStageBuyCarPopup.getChooseCity() == null) {
                showToast("请选择城市");
                return;
            }
            startActivityForResult(Shop4sChooseActivity.class, 12,
                    new BundleBuilder()
                            .putSerializable("carId", seriesId)
                            .putSerializable("location", customStageBuyCarPopup.getChooseCity())
                            .create());
        }
    }

    @Override
    public void onStageBuyCarPopupApplySubmit(String carid, String shopids, String phone, String name, String city) {
        mvpPresenter.addInstallment(carid, shopids, phone, name, city);
    }

    @Override
    public void onStageBuyCarPopupLookAgreement() {
        startActivity(WebActivity.class, new BundleBuilder().putString("url", Constants.YRL_CYHGRXXBHTK).create());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10:
                if (resultCode == RESULT_OK) {
                    CarInfo carInfo = (CarInfo) data.getSerializableExtra("carInfo");
                    if (carInfo != null && customStageBuyCarPopup != null) {
                        customStageBuyCarPopup.setChooseModel(carInfo);
                    }
                }
                break;
            case 11:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        BaiDuLocationInfo locationInfo = (BaiDuLocationInfo) data.getSerializableExtra("entity");
                        if (locationInfo != null && !StringUtils.isTrimEmpty(locationInfo.getCity()) && customStageBuyCarPopup != null) {
                            customStageBuyCarPopup.setChooseCity(locationInfo);
                        }
                    }
                }
                break;
            case 12:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        ArrayList<String> ids = data.getStringArrayListExtra("chooseList");
                        if (ids != null && ids.size() > 0 && customStageBuyCarPopup != null) {
                            customStageBuyCarPopup.setChooseMerchant(ids);
                        }
                    }
                }
                break;

            case 20:
                if (resultCode == RESULT_OK) {
                    CarInfo carInfo = (CarInfo) data.getSerializableExtra("carInfo");
                    if (carInfo != null && customInquiryPopup != null) {
                        customInquiryPopup.setChooseModel(carInfo);
                    }
                }
                break;
            case 21:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        BaiDuLocationInfo locationInfo = (BaiDuLocationInfo) data.getSerializableExtra("entity");
                        if (locationInfo != null && !StringUtils.isTrimEmpty(locationInfo.getCity()) && customInquiryPopup != null) {
                            customInquiryPopup.setChooseCity(locationInfo);
                        }
                    }
                }
                break;
            case 22:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        ArrayList<String> ids = data.getStringArrayListExtra("chooseList");
                        if (ids != null && ids.size() > 0 && customInquiryPopup != null) {
                            customInquiryPopup.setChooseMerchant(ids);
                        }
                    }
                }
                break;
            case 300:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        BaiDuLocationInfo locationInfo = (BaiDuLocationInfo) data.getSerializableExtra("entity");
                        if (locationInfo != null && !StringUtils.isTrimEmpty(locationInfo.getCity())) {
                            nowCity = locationInfo;
                            tvCity.setText(nowCity.getCity());
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void onInquiryPopupCallChooseModel() {
        startActivityForResult(ChooseCarModelActivity.class, 20,
                new BundleBuilder().putSerializable("seriesInfo", seriesInfo).create());
    }

    @Override
    public void onInquiryPopupCallChooseCity() {
        startActivityForResult(ChooseCityActivity.class, 21);
    }

    @Override
    public void onInquiryPopupCallChooseMerchant() {
        if (customInquiryPopup != null) {
            if (customInquiryPopup.getChooseModel() == null) {
                showToast("请选择车型");
                return;
            }
            if (customInquiryPopup.getChooseCity() == null) {
                showToast("请选择城市");
                return;
            }
            startActivityForResult(Shop4sChooseActivity.class, 22,
                    new BundleBuilder()
                            .putSerializable("carId", seriesId)
                            .putSerializable("location", customInquiryPopup.getChooseCity())
                            .create());
        }
    }

    @Override
    public void onInquiryPopupApplySubmit(String carid, String shopids, String phone, String name, String city) {
        mvpPresenter.addShopInquiry(carid, shopids, phone, name, city);
    }

    @Override
    public void onInquiryPopupLookAgreement() {
        startActivity(WebActivity.class, new BundleBuilder().putString("url", Constants.YRL_CYHGRXXBHTK).create());
    }

    @Subscribe
    public void onCarCompareRecodeDeleteEvent(CarCompareRecodeDeleteEvent event) {
        carModelAdapter.notifyDataSetChanged();
        setShowCompareCount();
    }
}
